import Koa from "koa";
import Router from "koa-router";
import assets from "koa-static";
import mime from "mime-types";
import {resolve} from "path";
import {readdirSync,statSync,readFileSync,existsSync} from "fs";
import dayjs from "dayjs";
import {formatFileSize} from "./utils.js";
import ejs from "ejs";

let app = new Koa();
let router = new Router();

let baseDir = resolve("files");
let templateFile = resolve("template.html");


app.use(assets(baseDir));

router.get("/",async (ctx)=>{

    let subDir = ctx.query.dir || "/";
    let targetDir = baseDir+subDir;

    let files = [];
    if(existsSync(targetDir)) {
        files = readdirSync(targetDir).reduce((previousValue,currentValue,currentIndex)=>{
            if(currentValue.startsWith(".")) return previousValue;
            if(currentValue === "desktop.ini") return previousValue;

            let fullPath = resolve(targetDir,currentValue);
            let stat =  statSync(fullPath);
            let isDirectory = stat.isDirectory();

            let fileMime = isDirectory ? undefined : mime.lookup(currentValue);
            let fileExt = isDirectory ? undefined : currentValue.split(".").pop();
            previousValue.push({
                path: subDir !== "/" ? [subDir,currentValue].join("/") : "/" + currentValue,
                name: currentValue,
                isDirectory,
                size: isDirectory ? 0:stat.size,
                sizeFormat: isDirectory ? 0 : formatFileSize(stat.size),
                mtime: dayjs(stat.mtime).format("YYYY-MM-DD HH:mm:ss"),
                birthtime: dayjs(stat.birthtime).format("YYYY-MM-DD HH:mm:ss"),
                ext: fileExt,
                mime: fileMime,
                isVideo: fileMime?.startsWith("video"),
                isImage: fileMime?.startsWith("image"),
                isZip: ["zip","rar","7z"].includes(fileExt)
            })
            return previousValue;
        },[]).sort((a,b)=>{
            return a.isDirectory ? -1:1;
        })
    }


    ctx.body = ejs.render(readFileSync(templateFile,{encoding:"utf-8"}),{files});
})

app.use(router.allowedMethods());
app.use(router.routes());

app.listen(8000,()=>{
    console.log("Running: http://localhost:8000");
})